package com.wss.common.base;

import com.wss.common.base.mvp.BasePresenter;
import com.wss.common.base.mvp.IBaseView;
import com.wss.common.utils.TextUtils;
import com.wss.common.widget.dialog.LoadingDialog;
import ohos.aafwk.ability.ILifecycle;
import ohos.aafwk.ability.Lifecycle;
import ohos.aafwk.ability.LifecycleObserver;
import ohos.aafwk.content.Intent;

public abstract class BaseMvpAbility<P extends BasePresenter> extends BaseAbility implements IBaseView {

    private P presenter;
    private LoadingDialog loadingDialog;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        loadingDialog = new LoadingDialog(context);
        loadingDialog.setCancelable(loadingCancelable());
        //创建present
        presenter = createPresenter();
        if (presenter != null) {
            presenter.attachView(this);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (presenter != null) {
            presenter.detachView();
            presenter = null;
        }
    }

    /**
     * 返回Presenter
     *
     * @return P
     */
    protected P getPresenter() {
        return presenter;
    }

    //***************************************IBaseView方法实现 start*************************************

    @Override
    public void showLoading() {
        showLoading("");
    }

    /**
     * 显示加载框
     *
     * @param msg 加载框文字
     */
    public void showLoading(String msg) {
        if (loadingDialog != null && !loadingDialog.isShowing()) {
            if (!TextUtils.isEmpty(msg)) {
                loadingDialog.setTitleText(msg);
            }
            loadingDialog.show();
        }
        hideEmptyView();
    }

    @Override
    public void dismissLoading() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    /**
     * 加载框是否可以取消
     *
     * @return boolean
     */
    protected boolean loadingCancelable() {
        return true;
    }


    @Override
    public void onEmpty(Object tag) {
        dismissLoading();
    }

    @Override
    public void onError(Object tag, String errorMsg) {
        dismissLoading();
    }

    @Override
    public Lifecycle getLifecycleOwner() {
        return getLifecycle();
    }

    //***************************************IBaseView方法实现 end*************************************

    /**
     * 创建Presenter
     *
     * @return Presenter
     */
    protected abstract P createPresenter();
}
